package ru.dc.gui.swing.settings;

import com.jidesoft.dialog.AbstractDialogPage;
import com.jidesoft.dialog.ButtonEvent;
import com.jidesoft.dialog.ButtonListener;
import ru.dc.Application;
import ru.dc.object.Settings;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.*;

/**
 * <pre>
 * User: Penkov Vladimir
 * Date: 02.11.2010
 * Time: 16:02:26
 * </pre>
 */
public class InfoPage extends AbstractDialogPage {

    private JTextField nick;
    private JTextField email;
    private JPanel rootPanel;
    private JComboBox encoding;

    public InfoPage() {
        setTitle("Сведения");
        nick.getDocument().addDocumentListener(new SimpleDocumentListener() {
            @Override
            public void onUpdate(DocumentEvent e) {
                nickUpdated();
            }
        });

        email.getDocument().addDocumentListener(new SimpleDocumentListener() {
            @Override
            public void onUpdate(DocumentEvent e) {
                emailUpdated();
            }
        });


        addButtonListener(new ButtonListener() {
            public void buttonEventFired(ButtonEvent e) {
                System.out.println("qq");
            }
        });


        setLayout(new BorderLayout());
        add(rootPanel, BorderLayout.CENTER);

    }

    public void apply() {
        Application.getApplication().getSettings().setNick(nick.getText());
        Application.getApplication().getSettings().setEmail(email.getText());
        Application.getApplication().getSettings().setEncoding(encoding.getSelectedItem().toString());
    }


    private void nickUpdated() {
        final String value = Application.getApplication().getSettings().getNick();
        if (!nick.getText().equals(value)) {
            firePropertyChange("nick", value, nick.getText());
        }
    }

    private void emailUpdated() {
        final String value = Application.getApplication().getSettings().getNick();
        if (!nick.getText().equals(value)) {
            firePropertyChange("nick", value, nick.getText());
        }
    }

    public void lazyInitialize() {
        final Settings settings = Application.getApplication().getSettings();
        nick.setText(settings.getNick()!=null ? settings.getNick() : "");
        email.setText(settings.getEmail()!=null ? settings.getEmail() : "");
        if (settings.getEncoding()!=null) {
            encoding.setSelectedItem(settings.getEncoding());
        }
    }



    private abstract class SimpleDocumentListener implements DocumentListener {
        public void insertUpdate(DocumentEvent e) {
            onUpdate(e);
        }

        public void removeUpdate(DocumentEvent e) {
            onUpdate(e);
        }

        public void changedUpdate(DocumentEvent e) {
            onUpdate(e);
        }

        public abstract void onUpdate(DocumentEvent e);
    }
}
